package com.aaron.http;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpsTest {
	public static String doPost(String url, Map<String,String> params,String charset){
		HttpClient httpClient = null;
		HttpPost   httpPost   = null;
		String     responseStr= null;
		try{
			httpClient = new SSLClient();  
            httpPost = new HttpPost(url); 
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            if(params != null){
	            Iterator<Entry<String,String>> it = params.entrySet().iterator();
	            while(it.hasNext()){
	            	Entry<String,String> entry = it.next();
	            	paramList.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
	            }
            }
            if(paramList.size() > 0){
            	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,charset);  
                httpPost.setEntity(entity); 
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
            	HttpEntity entity = response.getEntity();
            	if(entity != null){
            		responseStr = EntityUtils.toString(entity,charset);
            	}
            }
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return responseStr;
	}
	
	
	
	public static String doGet(String url, Map<String,String> params,String charset){
		HttpClient httpClient = null;
		HttpGet    httpGet    = null;
		String     responseStr= null;
		try{
			httpClient = new SSLClient();  
            if(params!=null && params.size() > 0){
            	url += "?";
            	Iterator<Entry<String,String>> it = params.entrySet().iterator();
            	while(it.hasNext()){
            		Entry<String,String> entry = it.next();
            		url += entry.getKey()+"="+entry.getValue()+"&";
            	}
            	url.substring(0, url.length()-2);
            }
            httpGet    = new HttpGet(url); 
            HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
            	HttpEntity entity = response.getEntity();
            	if(entity != null){
            		responseStr = EntityUtils.toString(entity,charset);
            	}
            }
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return responseStr;
	}
}
